package com.xy.smartsms.facade;

import android.content.Context;

import com.xy.smartsms.data.ISmsPlugin;
import com.xy.smartsms.pluginxy.XYSmsPlugin;
import com.xy.smartsms.util.Log;

import java.lang.reflect.Constructor;

import cn.com.xy.sms.sdk.action.AbsSdkDoAction;

public class SmsPluginManager {
    private static final String TAG = SmsPluginManager.class.getSimpleName();
    private ISmsPlugin mXYPlugin;
    private ISmsPlugin mCMCCPlugin;
    private Context mContext = null;
    private static SmsPluginManager sPluginManager = null;
    private boolean mHasCMCCPlugin = true;

    static public SmsPluginManager getInstance() {
        return sPluginManager;
    }

    static public SmsPluginManager getInstance(Context context) {
        synchronized (SmsPluginManager.class) {
            if (sPluginManager == null) {
                sPluginManager = new SmsPluginManager(context);
            }
        }

        return sPluginManager;
    }

    // TODO load from IPC to provide process independent implementation
    private SmsPluginManager(Context context) {
        mContext = context;
        mXYPlugin = new XYSmsPlugin(context);
    }

    public boolean loadCarrierPlugin() {
        if (mCMCCPlugin == null && mHasCMCCPlugin) {
            mCMCCPlugin = getCMCCSmsPlugin(mContext);
        }

        if (mCMCCPlugin == null) {
            mHasCMCCPlugin = false;
        }
        return mHasCMCCPlugin;
    }

    private ISmsPlugin getCMCCSmsPlugin(Context context) {
        try {
            Class cls = Class.forName("com.xy.smartsms.plugincmcc.CMCCSmsPlugin");  //import class
            Constructor cst = cls.getConstructor(new Class[]{Context.class}); //get the constructor
            Object obj = cst.newInstance(new Object[]{context}); //get a new instance
            return (ISmsPlugin) obj;
        } catch (Throwable t) {
            Log.d(TAG, "getCMCCSmsPlugin, t =" + t);
        }

        return null;
    }

    public void finalize() throws Throwable {

    }

    public ISmsPlugin getCustom() {
        return mCMCCPlugin;
    }

    public ISmsPlugin getCustom(int operator) {
        if (operator == AbsSdkDoAction.OPERATOR_CMCC) {
            return mCMCCPlugin;
        }

        return null;
    }

    public ISmsPlugin getDefault() {
        return mXYPlugin;
    }
}
